package utilities.display.imgs;

import java.awt.AlphaComposite;
import java.awt.Composite;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;

import utilities.display.iface.Drawable;

public class DrawImage implements Drawable 
{
	protected BufferedImage baseImg;
	protected AlphaComposite compositeRule;
	
	protected double scale;
	protected int x;
	protected int y;
	protected AffineTransform myTrans;
	
	public DrawImage(BufferedImage img, AlphaComposite composite, double scale, int x, int y)
	{
		this.baseImg = img;
		this.compositeRule = composite != null ? composite : AlphaComposite.SrcOver;
		this.scale = scale;
		this.x = x;
		this.y = y;
		
		resetTransform();
	}
	
	public void drawMe(Graphics g) 
	{
		if(baseImg != null)
		{
			Graphics2D g2 = (Graphics2D)g;
			
			// Get old settings
			Composite oldComp = g2.getComposite();
			AffineTransform oldTrans = g2.getTransform();
			
			// Set up transform
			//AffineTransform newTrans = new AffineTransform();
			//newTrans.scale(scale, scale);
			//newTrans.translate(x / scale, y / scale);
			//newTrans.translate(x, y);
			//g2.setTransform(newTrans);
			
			// Set up opacity
			if(compositeRule != null) g2.setComposite(compositeRule);
			
			// Draw the image
			//g2.drawImage(baseImg, newTrans, null);
			g2.drawImage(baseImg, myTrans, null);
			
			// Restore old settings
			g2.setComposite(oldComp);
			g2.setTransform(oldTrans);
			//g2.scale(1, 1);
		}
	}
	
	public void translate(int dx, int dy)
	{
		this.x += dx;
		this.y += dy;
		
		resetTransform();
	}
	
	public void setComposite(AlphaComposite composite)
	{
		this.compositeRule = composite != null ? composite : AlphaComposite.SrcOver;
	}
	
	public void setScale(double scale)
	{
		this.scale = scale;
		
		resetTransform();
	}
	
	public double getScale()
	{
		return scale;
	}
	
	public Rectangle getArea()
	{
		return baseImg != null ? new Rectangle(x, y, (int)(baseImg.getWidth() * this.scale), (int)(baseImg.getHeight() * this.scale)) : null;
		//return baseImg != null ? new Rectangle(x, y, (int)(baseImg.getWidth() * this.scale), (int)(baseImg.getHeight() * this.scale)) : null;
	}
	
	public boolean contains(int x, int y)
	{
		return getArea().contains(x, y);
	}

	private void resetTransform() 
	{
		myTrans = new AffineTransform();
		myTrans.scale(this.scale, this.scale);
		myTrans.translate(this.x / this.scale, this.y / this.scale);
	}
}
